package com.bainuo.doctor.common.util;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;

import com.blankj.utilcode.utils.LogUtils;

import java.io.File;
import java.io.IOException;

public class AudioPlayer {

	public static interface OnCompletionCallBack {
		public void onCompletionCallBack(int type);
	}
	public static final int INT_START = 0;
	public static final int INT_STOP = INT_START+ 1;

	public Object tag;
	private final String TAG = AudioPlayer.class.getSimpleName();
	private MediaPlayer mMediaPlayer;
	private Context mContext = null;
	public static boolean isPlayer = false;//播放状态

	
	private OnCompletionCallBack mOnCompletionCallBack = null;


	private Handler mHandler;
	public void setOnCompletionCallBack(OnCompletionCallBack l){
		mOnCompletionCallBack = l;
	}
	public AudioPlayer(Context context, Handler handler){
		mContext = context;
		mHandler = handler;
	}
	public boolean playAudio(String path){
		boolean ret = false ;
		try {
			if(!isPlayer){
				isPlayer = true;
				mMediaPlayer = new MediaPlayer();
				mMediaPlayer.setDataSource(path);
				mMediaPlayer.prepare();
				mMediaPlayer.start();
				mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
					
					@Override
					public void onCompletion(MediaPlayer mp) {
						if(isPlayer)
						{
							isPlayer = false;
							//播放完成
							if(mOnCompletionCallBack != null){
								mOnCompletionCallBack.onCompletionCallBack(INT_START);
							}
						}
					}
				});
			}else{
				isPlayer = false;
				stopAudio();
			}
			ret = true;
		} catch (Exception e) {
			LogUtils.e(TAG, "audio play failed:",e);
		}
		return ret;
	}

	public MediaPlayer getmMediaPlayer() {
		return mMediaPlayer;
	}




	/**
	 * 停止当前，并播放下一段
	 * */
	public boolean playAnotherAudio(String path){
		boolean ret = false ;
		try {
			if(isPlayer){
				isPlayer = false;
				stopAudio();
			}
			if(!isPlayer){
				isPlayer = true;
				mMediaPlayer = new MediaPlayer();
				mMediaPlayer.setDataSource(path);
				mMediaPlayer.prepare();
				mMediaPlayer.start();
				mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
					
					@Override
					public void onCompletion(MediaPlayer mp) {
						if(isPlayer)
						{
							isPlayer = false;
							//播放完成
							if(mOnCompletionCallBack != null){
								mOnCompletionCallBack.onCompletionCallBack(INT_START);
							}
						}
					}
				});
			}
			ret = true;
		} catch (Exception e) {
			LogUtils.e(TAG, "audio play failed:",e);
		}
		return ret;
	}
	public boolean stopAudio(){
		boolean ret = false;
		if(null != mMediaPlayer){
			try {
				mMediaPlayer.stop();
				isPlayer = false;
				ret = true;
				if(mOnCompletionCallBack != null){
					mOnCompletionCallBack.onCompletionCallBack(INT_STOP);
				}
			} catch (Exception e) {
				LogUtils.e(TAG, "audio stop failed:",e);
			}
			mMediaPlayer.release();
			if (mHandler != null)
				mHandler.removeMessages(0,null);
			mMediaPlayer = null;
		}
		return ret;
	}
	public boolean resumeAudio(){
		boolean ret = false;
		if(null != mMediaPlayer && !mMediaPlayer.isPlaying()){
			try {
				mMediaPlayer.start();
				ret = true;
			} catch (Exception e) {
				LogUtils.e(TAG, "audio resume failed:",e);
			}
		}
		return ret;
	}
	public boolean pauseAudio(){
		boolean ret = false;
		if(null != mMediaPlayer && mMediaPlayer.isPlaying()){
			try {
				mMediaPlayer.pause();
				ret = true;
			} catch (Exception e) {
				LogUtils.e(TAG, "audio pause failed:",e);
			}
		}
		return ret;
	}

	public boolean isPlaying(){
		return  (mMediaPlayer != null && mMediaPlayer.isPlaying());
	}
	public int getPos(){
		return  (mMediaPlayer == null || !isPlayer)?0:mMediaPlayer.getCurrentPosition();
	}

	
	/*********************        录音功能                  ***********************/
	public MediaRecorder recorder;
	private boolean isRecording;

	public void startRecord(String path) throws Exception {
		String state = Environment.getExternalStorageState();
		if (!state.equals(Environment.MEDIA_MOUNTED)) {
			throw new IOException("SD Card is not mounted,It is  " + state
					+ ".");
		}
		File directory = new File(path).getParentFile();
		if (!directory.exists() && !directory.mkdirs()) {
			throw new IOException("Path to file could not be created");
		}
		if (recorder != null) {
			recorder.release();
			recorder = null;
		}
		recorder = new MediaRecorder();
		recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
		recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
		recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
		recorder.setAudioSamplingRate(8000);
		recorder.setOutputFile(path);
		recorder.prepare();
		recorder.start();

		isRecording = true;
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					while (isRecording && mHandler != null) {
						android.os.Message msg = new android.os.Message();
						msg.what = recorder.getMaxAmplitude() * 8 / 0x7FFF;
						if (mHandler != null)
							mHandler.sendMessage(msg);
						SystemClock.sleep(100);
					}
				} catch (Exception e) {
					// from the crash report website, found one NPE crash from
					// one android 4.0.4 htc phone
					// maybe handler is null for some reason
					LogUtils.e("voice", e.toString());
				}
			}
		}).start();
	}

	public void stopRecord() throws Exception {
		isRecording = false;
		if(recorder!=null){
			recorder.stop();
			recorder.release();
			recorder = null;
		}
		
	}

	public int getAmplitude() {
		if (recorder != null) {
			return (recorder.getMaxAmplitude());
		} else
			return 0;
	}
	

}
